<?php
namespace app\admin\controller;

use think\Db;

class Apimgr extends Base{

	public function index() {
		$apicate = DB::name('api_cfg')->where([
			'is_cate' => 1
		])->select();
		$data = [];
		foreach($apicate as $k => $v){
			$data[$v['id']] = $v;
			$data[$v['id']]['item'] = DB::name('api_cfg')->where([
				'cate_id' => $v['id']
			])->select();
		}
		$this->assign([
			'cateArr' => $data
		]);
		return $this->fetch();
	}
	/**
	 * [获取表单数据]
	 */
	public function getForm() {
		$apicate = DB::name('api_cfg')->where([
			'is_cate' => 1
		])->select();
		$data = [];
		foreach($apicate as $k => $v){
			$item = DB::name('api_cfg')->where([
				'cate_id' => $v['id']
			])->select();
			$data['cfgForm_'.$v['id']] = [];
			foreach($item as $ke => $va){
				$data['cfgForm_'.$v['id']]['id_'.$va['id']] = $va;
			}
		}
		return ['code'=>1,'msg'=>'加载成功','data'=>$data];
	}

	/**
	 * [新增配置]
	 */
	public function newCfg() {
		$param = input('post.');
		if($param['label'] == ''){
			return ['code'=>0,'msg'=>'名称不能为空'];
		}
		DB::startTrans();
		try{
			DB::name('api_cfg')->insert($param);
			DB::commit();
			return ['code'=>1,'msg'=>'添加成功'];
		}catch(\Exception $e){
			DB::rollback();
			return ['code'=>0,'msg'=>'添加失败:'.$e->getMessage()];
		}
	}

	/**
	 * [删除配置]
	 */
	public function delCfg() {
		$id = input('post.id');
		$res = DB::name('api_cfg')->where('id',$id)->delete();
		if($res === false){
			return ['code'=>0,'msg'=>'删除失败'];
		}else{
			return ['code'=>1,'msg'=>'删除成功'];
		}
	}

	/**
	 * [编辑配置]
	 */
	public function editCfg() {
		$param = input('post.');
		DB::startTrans();
		try{
			foreach($param as $v){
				DB::name('api_cfg')->where('id',$v['id'])->update($v);
			}
			DB::commit();
			return ['code'=>1,'msg'=>'保存成功'];
		}catch(\Exception $e){
			DB::rollback();
			return ['code'=>0,'msg'=>'保存失败:'.$e->getMessage()];
		}
	}

	/**
	 * [删除配置分类]
	 */
	public function delCate() {
		$cate_id = input('post.cate_id');
		DB::startTrans();
		try{
			DB::name('api_cfg')->where('id',$cate_id)->whereOr('cate_id',$cate_id)->delete();
			DB::commit();
			return ['code'=>1,'msg'=>'删除成功'];
		}catch(\Exception $e){
			DB::rollback();
			return ['code'=>0,'msg'=>'删除失败:'.$e->getMessage()];
		}
	}
}
